package cn.f.generator;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成器
 * @author fupengcheng
 */
public class CodeGenerator {

    public static void main(String[] args) {


        //表如果没有主键的话，生成的mapper.xml 文件末尾会多一个逗号

        //子模块名称
        String projectModelName = StringPool.SLASH + "mmbearingcapacity";
        //包路径
        String packagePath = "com.mmbearingcapacity";

        //二级模块分类名称
        String packMdName = "migrate";

        String author="fpc";

        Boolean isParamCheck=false;// 请求实体是否支持@ParamCheck 参数  false 不支持

        // 要生成的表名称
        String[] tables = {"photov_transit_projects_info","photov_mid_voltage_active","photov_low_over_power"};//,"dis_evaluate"


        //数据源配置
     /*   DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDriverName("dm.jdbc.driver.DmDriver");
        dataSourceConfig.setUrl("jdbc:dm://localhost:5236");
        dataSourceConfig.setUsername("SYSDBA");
        dataSourceConfig.setPassword("Root2025");
        dataSourceConfig.setDbType(DbType.DM);*/


        //本地pg
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDriverName("org.postgresql.Driver");
        dataSourceConfig.setUrl("jdbc:postgresql://127.0.0.1:5432/postgres?currentSchema=migration_orbit");
        dataSourceConfig.setUsername("postgres");
        dataSourceConfig.setPassword("root");
        dataSourceConfig.setDbType(DbType.POSTGRE_SQL);
        dataSourceConfig.setSchemaName("migration_orbit");

        /*DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDriverName("org.postgresql.Driver");
        dataSourceConfig.setUrl("jdbc:postgresql://192.168.1.100:5432/postgres?currentSchema=disribution_network");
        //jdbc:postgresql://192.168.125.5:5432/testdb
        dataSourceConfig.setUsername("postgres");
        dataSourceConfig.setPassword("postgres");
        dataSourceConfig.setDbType(DbType.POSTGRE_SQL);
        dataSourceConfig.setSchemaName("disribution_network");*/


        //代码生成器
        AutoGenerator generator = new AutoGenerator();

        generator.setDataSource(dataSourceConfig);

        //全局配置
        GlobalConfig gc = new GlobalConfig();
        //模版输出路径
        //项目源码文件路径
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + projectModelName + "/src/main/java");
        //根据系统用户名称,设置类的作者名称
        gc.setAuthor(author);
        gc.setOpen(Boolean.TRUE);
        // Mapper生成名称的策略,实体类名+Mapper
        gc.setMapperName("%sMapper");
        //设置Service接口的命名策略, 实体类名+Manager
        gc.setServiceName("%sService");
        //设置Service实现类的命名策略, 实体类名+ManagerImpl
        gc.setServiceImplName("%sServiceImpl");

        //覆盖相同的文件
        gc.setFileOverride(Boolean.TRUE);
        gc.setActiveRecord(Boolean.TRUE);
        gc.setBaseResultMap(Boolean.TRUE);
//        gc.setEnableCache(Boolean.TRUE);
        gc.setSwagger2(Boolean.TRUE);
        generator.setGlobalConfig(gc);


        //策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        //设置要生成的表
        strategyConfig.setInclude(tables);
//        strategyConfig.setEntityBuilderModel(Boolean.TRUE);

        generator.setStrategy(strategyConfig);

        //包配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent(packagePath);
        packageConfig.setEntity("model.dto."+packMdName);
        //设置 service 的输出目录
        packageConfig.setService("service."+packMdName);
        //设置 service impl 的输出目录
        packageConfig.setServiceImpl("service."+packMdName+".impl");
        packageConfig.setController("controller."+packMdName);
        packageConfig.setMapper("dao."+packMdName);
        packageConfig.setModuleName(null);

        generator.setPackageInfo(packageConfig);

        //cfg配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String,Object> map = new HashMap<String,Object>(16);
                map.put("packagePath", packagePath);
                map.put("moduleName", null == packageConfig.getModuleName() ?
                        StringUtils.EMPTY : packageConfig.getModuleName() + StringPool.DOT);
                //二级分类包名称
                map.put("packMdName", packMdName);

                map.put("isParamCheck", isParamCheck);
                this.setMap(map);
            }
        };

        //调整输出位置
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();

        //指定XML生成的位置
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + projectModelName + "/src/main/resources/mapper/"
                        + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });


        focList.add(new FileOutConfig("/templates/entityModel.java.vm" ) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //生成的类名称 (例如：usernameModel.java)
                String className = tableInfo.getEntityName() + "RespVO" + StringPool.DOT_JAVA;
                //包路径转目录路径(例如：com.upt.demo -> com/upt/demo)
                String path = packagePath.replace(StringPool.DOT, StringPool.SLASH);
                return projectPath + projectModelName +"/src/main/java/" + path
                        + "/model/vo/resp/" + className;
            }
        });

        focList.add(new FileOutConfig("/templates/entityModelreq.java.vm" ) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //生成的类名称 (例如：usernameModel.java)
                String className = tableInfo.getEntityName() + "ReqVO" + StringPool.DOT_JAVA;
                //包路径转目录路径(例如：com.upt.demo -> com/upt/demo)
                String path = packagePath.replace(StringPool.DOT, StringPool.SLASH);
                 tableInfo.getFields().forEach((l)->{
                     l.setType(extractContentInsideParentheses(l.getType()));
                });
                return projectPath + projectModelName +"/src/main/java/" + path
                        + "/model/vo/req/" + className;
            }
        });
        cfg.setFileOutConfigList(focList);

        generator.setCfg(cfg);

        TemplateConfig templateConfig = new TemplateConfig();
        //不生成默认的XML
        templateConfig.setXml(null);

        generator.setTemplate(templateConfig);

        generator.execute();
    }

    public static String extractContentInsideParentheses(String input) {

        //  判断是否为正整数（不含零，不含负号）
        if (input.matches("^[1-9]\\d*$")) {
            return input; // 是正整数，不处理
        }

        if (input == null || !input.contains("(") || !input.contains(")")) {
            return "8";
        }

        int startIndex = input.indexOf("(") + 1;
        int endIndex = input.indexOf(")", startIndex);

        if (startIndex >= endIndex || endIndex == -1) {
            return "32";
        }

        return input.substring(startIndex, endIndex);
    }


}
